<template>
  <div class="app-container">
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.number"  clearable />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="queryParams.username"  clearable />
        </el-form-item>
        <el-form-item label="审批人">
          <el-input v-model="queryParams.appName"  clearable />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
              v-model="queryParams.status"
              placeholder="单据状态"
              clearable
          >
            <el-option label="封停" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
              v-model="recTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
              v-model="appTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-row>
    <el-row>
      <el-col>

        <el-button  type="success" :icon="Plus" plain @click="addPage">新增退换货记录</el-button>
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow">删除</el-button>
        <el-button type="warning" :icon="Upload" plain @click="exportForm" >导出</el-button>

      </el-col>
    </el-row>
    <el-row >
      <el-table
          :data="userList"
          border
          stripe
          style="height: 545px"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
            prop="msgId"
            label="ID"
            width="80"
        />
        <el-table-column
            prop="msgOrderNo"
            label="退换货单号"
            width="250"
        />
        <el-table-column
            prop="msgType"
            label="退换货类型"
            width="100"
        >
          <template #default="scope">
            <el-text v-if="scope.row.type == 1"  type="primary">退货</el-text>
            <el-text v-else-if="scope.row.type == 2" type="danger">换货</el-text>
          </template>
        </el-table-column>
        <el-table-column
            prop="msgUsername"
            label="申请人"
        />
        <el-table-column label="申请时间" width="200">
          <template #default="scope">
            {{ formatLoginTime(scope.row.msgCreateTime) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="msgAppId"
            label="审批人"
        />
        <el-table-column label="最后更新时间" width="200">
          <template #default="scope">
            {{ formatLoginTime(scope.row.msgUpdateTime) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="msgStatus"
            label="单据状态"
        >
          <template #default="scope">
            <el-text v-if="scope.row.msgType == 0"  type="warning">待审核</el-text>
            <el-text v-else-if="scope.row.msgType == 1" type="primary">审核通过</el-text>
            <el-text v-if="scope.row.msgType == 2"  type="danger">审核驳回</el-text>
            <el-text v-else-if="scope.row.msgType == 3" type="warning">待寄回</el-text>
            <el-text v-if="scope.row.msgType == 4"  type="primary">已寄回</el-text>
            <el-text v-else-if="scope.row.msgType == 5" type="primary">处理中</el-text>
            <el-text v-if="scope.row.msgType == 6"  type="success">已完成</el-text>
            <el-text v-else-if="scope.row.msgType == 7" type="info">已取消</el-text>
          </template>
        </el-table-column>

        <el-table-column label="操作" default="scope">
          <template #default="scope">
            <el-button type="primary" size="small" @click="check(scope.row)">查看</el-button>
            <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>

            <el-button type="danger" size="small" @click="deleteOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="24">

        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>
  </div>

  <!-- 添加用户信息 -->
  <el-dialog
      v-model="editFormVisible"
      :title="editTitle"
      width="900px"
      append-to-body
  >
    <!-- 滚动容器：确保滚动条紧邻表单 -->
    <div class="form-scroll-container">
      <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="80px"
      >

        <!-- 订单基本资料 -->
        <div class="form-section">
          <h3 class="section-title">订单基本资料</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单编号">
                <el-input v-model="editForm.omOrder.ooOrderCode" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下单日期">
                <el-input v-model="editForm.omOrder.ooOrderTime" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单类型">
                <el-input v-model="editForm.omOrder.ooOrderType" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单动作">
                <el-input v-model="editForm.omOrder.ooOrderAction" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务类型">
                <el-input v-model="editForm.omOrder.ooBussinessType" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单状态">
                <el-input v-model="editForm.omOrder.ooOrderState" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>




        <!-- 收货人资料 -->
        <div class="form-section">
          <h3 class="section-title">收货人资料</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货人">
                <el-input v-model="editForm.omOrder.ooCneeName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员帐号">
                <el-input v-model="editForm.omOrder.ooCneeAccount" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="editForm.omOrder.ooCneePhone" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系手机">
                <el-input v-model="editForm.omOrder.ooCneeCellphone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮政编码">
                <el-input v-model="editForm.omOrder.ooCneePostalCode" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货地址">
                <el-input v-model="editForm.omOrder.ooCneeAddress" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配送地区">
                <el-input v-model="editForm.omOrder.ooCneeDeliArea" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配送方式">
                <el-input v-model="editForm.omOrder.ooCneeDeliWay" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配送费用">
                <el-input v-model="editForm.omOrder.ooCneeDeliFare" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付方式">
                <el-input v-model="editForm.omOrder.ooCneeDeliMethod" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电子邮箱">
                <el-input v-model="editForm.omOrder.ooCneeEmail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="editForm.omOrder.ooRemark" type="textarea" rows="2" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>





        <!-- 订单商品信息 -->
        <div class="form-section">
          <h3 class="section-title">订单商品信息</h3>
          <el-table :data="[editForm.omOrderGoods]" border style="width: 100%; margin-bottom: 15px" size="small" v-if="editForm.omOrderGoods && editForm.omOrderGoods.oogId">
            <el-table-column prop="oogGoodsCode" label="商品串码" width="100" />
            <el-table-column prop="oogOrderCode" label="订单编号" />
            <el-table-column prop="oogCount" label="数量" width="80" />
            <el-table-column prop="oogPrice" label="单价" width="100" />
          </el-table>
        </div>




        <!-- 订单退换商品信息 -->
        <div class="form-section">
          <h3 class="section-title">订单退换商品信息</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品串码">
                <el-input v-model="editForm.omOrderGoods.oogGoodsCode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称">
                <el-input v-model="editForm.tspu.spuName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编号">
                <el-input v-model="editForm.tspu.spuNo" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="退换类型">
                <el-select v-model="editForm.msgType" placeholder="请选择">
                  <el-option label="退货" :value="1" />
                  <el-option label="换货" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退换原因">
                <el-select v-model="editForm.msgReasonType" placeholder="请选择">
                  <el-option label="质量问题" :value="1" />
                  <el-option label="尺寸不符" :value="2" />
                  <el-option label="七天无理由" :value="3" />
                  <el-option label="其它" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细原因">
                <el-input v-model="editForm.msgReasonDetail" type="textarea" rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
  Upload,
  Download
} from '@element-plus/icons-vue'
import {ref,onMounted,computed} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox} from "element-plus";
import loginUser from "@/stores/LoginUser.js";
let searchTime = ref(["",""])
let queryParams =ref({})
let userList = ref([])
let isSelectRow = ref(false)
let isAdd= ref(false);
const tableRef = ref(null);
const selectedRows = ref([]);
let proCityList = ref([])
let selectedRegion = ref([])
let selectedReg = ref([])
// let editForm = ref({})




const editForm = ref({
  // B2cReturnMsg 基础字段
  msgId: '',
  msgOrderNo: '',
  msgOriginalOrderId: '',
  msgUserId: '',
  msgType: '',
  msgReasonType: '',
  msgReasonDetail: '',
  msgStatus: '',
  msgCreateTime: '',
  msgUpdateTime: '',
  msgIsDeleted: '',
  msgAppId: '',
  msgUsername: '',

  // 关联对象
  omOrder: {
    ooId: '',
    ooOrderCode: '',
    ooOrderTime: '',
    ooOrderType: '',
    ooOrderAction: '',
    ooBussinessType: '',
    ooOrderState: '',
    ooCneeName: '',
    ooCneeAccount: '',
    ooCneePhone: '',
    ooCneeCellphone: '',
    ooCneePostalCode: '',
    ooCneeAddress: '',
    ooCneeDeliArea: '',
    ooCneeDeliWay: '',
    ooCneeDeliFare: '',
    ooCneeDeliMethod: '',
    ooCneeEmail: '',
    ooRemark: '',
    ooUpdateTime: ''
  },

  omOrderGoods: {
    oogId: '',
    oogGoodsCode: '',
    oogOrderCode: '',
    oogCount: '',
    oogPrice: ''
  },

  tspu: {
    id: '',
    spuNo: '',
    spuName: '',
    categoryId: '',
    firstCategoryId: '',
    firstCategoryName: '',
    secondCategoryId: '',
    secondCategoryName: '',
    brandId: '',
    unit: '',
    spuMoney: '',
    mainPicUrl: '',
    detailHtml: '',
    status: '',
    sortOrder: '',
    createdTime: '',
    updatedTime: '',
    isDeleted: '',
    brandName: '',
    categoryName: ''
  },

  // 退换货商品信息（用于表单展示）
  returnGoods: {
    goodsCode: '',
    goodsName: '',
    goodsBrand: '',
    goodsModel: '',
    goodsColor: '',
    returnType: '',
    exchangeName: '',
    returnReason: '',
    repairNo: '',
    applyTime: '',
    repairPoint: '',
    repairPhone: '',
    returnRemark: ''
  },

  // 商品列表（用于表格展示）
  goodsList: []
});



let resetQueryForm=()=>{
  queryParams.value = {
    pageNum:1,
    pageSize:10,
    number:'',
    username:'',
    appName:'',
    status:'',
    total:'',
  }
  // 重置级联选择器
  selectedRegion.value = []
}

const props = {
  value: 'repLabel', // 指定选项中作为“值”的字段（如后端返回的地区ID）
  label: 'repVal', // 指定选项中作为“显示文本”的字段（如地区名称）
  children: 'childRep', // 指定选项中作为“子选项列表”的字段（如后端返回的子地区列表字段）
  expandTrigger: 'hover',//鼠标悬浮时显示子数据
};

let query = ()=>{
  // if (searchTime.value[0]!==''){
  //   queryParams.value.beginTime = formatDay(searchTime.value[0])
  //   queryParams.value.endTime = formatDay(searchTime.value[1])
  // }
  api.get('/mag/query',queryParams.value).then(res=>{
    console.log( res)
    userList.value = res.data.list
    queryParams.value.total = res.data.total
  })

}



// 添加级联选择器变化的处理方法
const handleChange = (value) => {
  if (value && value.length) {
    queryParams.value.pro = value[0]; // 省份值
    queryParams.value.city = value[1] || ''; // 城市值，可能不存在
  } else {
    queryParams.value.pro = '';
    queryParams.value.city = '';
  }
};

// // 添加级联选择器变化的处理方法
// const onChange = (value) => {
//   if (value && value.length) {
//     editForm.value.repPro = value[0]; // 省份值
//     editForm.value.repCity = value[1] || ''; // 城市值，可能不存在
//   } else {
//     editForm.value.repPro = '';
//     editForm.value.repCity = '';
//   }
// };

let switchHandler = (row)=>{
  ElMessageBox.confirm('是否修改用户['+row.id+']的状态？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (row.status == 1){
      row.status = '0'
    }else {
      row.status = '1'
    }
    console.log(row)
    api.post('/repair/save/update',row).then(res=>{
      ElMessage.success('修改成功')
      //query()
    })
  }).catch(() => {
    ElMessage.info('已取消修改');
  })

}
let editFormVisible = ref(false)

let editTitle = ref('编辑')
let addPage = ()=>{
  editFormVisible.value = true
  isAdd.value = true
  editTitle.value = "新增用户"
  reset()
}
let editFormRules = {
  repName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  repNumber: [
    { required: true, message: '请输入正确的手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, trigger: 'blur' }
  ],
  repAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],


  appealName: [
    { required: true, message: '请输入申诉记录名称', trigger: 'blur' }
  ],
  appealSource: [
    { required: true, message: '请选择申诉来源', trigger: 'change' }
  ],
  appealDesc: [
    { required: true, message: '请输入申诉记录描述', trigger: 'blur' }
  ],
  orderNo: [
    { required: true, message: '请输入订单编号', trigger: 'blur' }
  ],
  orderDate: [
    { required: true, message: '请选择下单日期', trigger: 'change' }
  ],
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入联系手机', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  receiverAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  returnReason: [
    { required: true, message: '请填写退换货原因', trigger: 'blur' }
  ]

}
let edit = (row)=>{
  console.log(row)

  editFormVisible.value = true
  isAdd.value = false
  editTitle.value = "退换货申请单"
  // editForm = ref(row)
  //因为editForm这个响应式遍历的值改变了，save方法中发请求用到了editForm的数据，故会调用自动save方法
  // 正确地更新响应式数据
  // Object.assign(editForm.value, row)
  // 正确地合并对象，确保嵌套对象也被正确复制
  editForm.value = {
    ...editForm.value,  // 保留默认结构
    ...row,             // 覆盖基础字段
    omOrder: row.omOrder ? { ...editForm.value.omOrder, ...row.omOrder } : editForm.value.omOrder,
    omOrderGoods: row.omOrderGoods ? { ...editForm.value.omOrderGoods, ...row.omOrderGoods } : editForm.value.omOrderGoods,
    tspu: row.tspu ? { ...editForm.value.tspu, ...row.tspu } : editForm.value.tspu
  }

  // // 设置级联选择器的初始值
  // if (row.repPro && row.repCity) {
  //   selectedReg.value = [row.repPro, row.repCity]
  // } else {
  //   selectedReg.value = []
  // }
}
/** 取消按钮 */
function cancel() {
  editFormVisible.value = false;
  reset();
}
function reset() {
  editForm.value = {
    // B2cReturnMsg 基础字段
    msgId: '',
    msgOrderNo: '',
    msgOriginalOrderId: '',
    msgUserId: '',
    msgType: '',
    msgReasonType: '',
    msgReasonDetail: '',
    msgStatus: '',
    msgCreateTime: '',
    msgUpdateTime: '',
    msgIsDeleted: '',
    msgAppId: '',
    msgUsername: '',

    // 关联对象
    omOrder: {
      ooId: '',
      ooOrderCode: '',
      ooOrderTime: '',
      ooOrderType: '',
      ooOrderAction: '',
      ooBussinessType: '',
      ooOrderState: '',
      ooCneeName: '',
      ooCneeAccount: '',
      ooCneePhone: '',
      ooCneeCellphone: '',
      ooCneePostalCode: '',
      ooCneeAddress: '',
      ooCneeDeliArea: '',
      ooCneeDeliWay: '',
      ooCneeDeliFare: '',
      ooCneeDeliMethod: '',
      ooCneeEmail: '',
      ooRemark: '',
      ooUpdateTime: ''
    },

    omOrderGoods: {
      oogId: '',
      oogGoodsCode: '',
      oogOrderCode: '',
      oogCount: '',
      oogPrice: ''
    },

    tspu: {
      id: '',
      spuNo: '',
      spuName: '',
      categoryId: '',
      firstCategoryId: '',
      firstCategoryName: '',
      secondCategoryId: '',
      secondCategoryName: '',
      brandId: '',
      unit: '',
      spuMoney: '',
      mainPicUrl: '',
      detailHtml: '',
      status: '',
      sortOrder: '',
      createdTime: '',
      updatedTime: '',
      isDeleted: '',
      brandName: '',
      categoryName: ''
    },

    // 退换货商品信息（用于表单展示）
    returnGoods: {
      goodsCode: '',
      goodsName: '',
      goodsBrand: '',
      goodsModel: '',
      goodsColor: '',
      returnType: '',
      exchangeName: '',
      returnReason: '',
      repairNo: '',
      applyTime: '',
      repairPoint: '',
      repairPhone: '',
      returnRemark: ''
    },

    // 商品列表（用于表格展示）
    goodsList: []
  }

  // 重置级联选择器
  selectedReg.value = []
}

function save() {

   //手动验证级联选择器
  if (!selectedReg.value || selectedReg.value.length === 0) {
    ElMessage.error('请选择所在城市')
   return
  }

  // 同步数据到 editForm
  editForm.value.repPro = selectedReg.value[0] || ''
  editForm.value.repCity = selectedReg.value[1] || ''

  api.post('/repair/save/update',editForm.value).then(res=>{
    if (res.code == 200){
      ElMessage.success("添加/修改成功")
      cancel()
      query()
    }else {
      ElMessage.error(res.msg)
    }

  })
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};
const deleteSelectedRows = () => {
  const idsArray = selectedRows.value.map(row => row.id);
  ElMessageBox.confirm('是否确认删除用户编号为['+idsArray+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    //ids变成,分割的字符串
    const ids = selectedRows.value.map(row => row.id).join(',');
    api.delete('/repair/delete/'+ids).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};
let deleteOne = (row)=>{
  ElMessageBox.confirm('是否确认删除用户编号为['+row.id+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
     api.delete('/repair/delete/'+row.id).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
 }

 function queryRroCityList(){
    api.get('/repair/pro/city').then(res=>{
      proCityList.value = res.data
    })
 }


onMounted(()=>{
  resetQueryForm();
  queryRroCityList();
  query();
})




</script>



<style scoped>
/* 滚动容器样式 - 确保滚动条紧邻表单 */
.form-scroll-container {
  max-height: 600px; /* 适当增加高度，让内容更舒展 */
  overflow-y: auto;  /* 内容超出时显示滚动条 */
  padding-right: 10px; /* 预留滚动条空间，避免遮挡内容 */
}

/* 区域标题样式 */
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0 10px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}

/* 表单项间距优化 */
:deep(.el-form-item) {
  margin-bottom: 12px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>